import express from 'express';
import mongoose from 'mongoose';
import bcryptjs from 'bcryptjs';
import jwt from 'jsonwebtoken';
import cors from 'cors';
import dotenv from 'dotenv';
import User from './models/User.js';
import authRouter from './routes/auth.js';
import moviesRouter from './routes/movies.js';
import ordersRouter from './routes/orders.js';
import userRouter from './routes/users.js';

dotenv.config();

const app = express();

// 中间件
app.use(cors());
app.use(express.json());

// 连接MongoDB
const mongoUri = process.env.MONGODB_URI || `mongodb://${process.env.MONGODB_USER}:${process.env.MONGODB_PASSWORD}@localhost:27017/auth_db?authSource=admin`;
mongoose.connect(mongoUri)
  .then(async () => {
    console.log('MongoDB connected');
    
    // 检查默认管理员账户是否存在
    const adminUser = await User.findOne({ username: 'admin' });
    if (!adminUser) {
      // 创建默认管理员账户
      const hashedPassword = await bcryptjs.hash('123456', 10);
      const admin = new User({
        username: 'admin',
        password: hashedPassword,
        role: 'admin'
      });
      await admin.save();
      console.log('默认管理员账户已创建');
    }
  })
  .catch(err => console.error('MongoDB connection error:', err));



// 注册路由
app.use('/api/auth', authRouter);
app.use('/api/movies', moviesRouter);
app.use('/api/orders', ordersRouter);
app.use('/api/users', userRouter);

const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});